<?php
/**
 * 用户管理
 * User: cxm
 * Date: 2020/8/17
 * Time: 11:29
 */
namespace App\Http\Controllers\Admin\Member;
use App\Http\Controllers\Admin\Controller;
use App\Models\User;
use Carbon\Carbon;
use Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class MemberController extends Controller {
    /**
     * 用户列表
     * URL POST:/admin/member/get-lists
     * @param Request $request
     * @param int type 用户类型 1个人2企业
     * @param int search_type 查询类型 1用户手机 2邮箱 3 昵称 4 真实名称
     * @param string keyword 关键字
     * @param int status 状态  1正常 2冻结
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['type','keyword','page','limit','status','is_check']);
        // 关键字
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        $type = isset($params['type']) ? $params['type'] : 1;

        if (!empty($keyword)) {
            switch ($type) {
                case 1:// 用户名称
                    $params['where'][] = ['name','like','%'.$keyword.'%'];
                    break;
                case 2:
                    $params['where'][] = ['mobile','like','%'.$keyword.'%'];
                    break;
            }
        }

        // 关联头像
        $params['with'][] = ['file'=>function($query){
            $query->select('id','path');
        }];
        // 微信信息
        $params['with'][] = 'weixin';
        \DB::enableQueryLog();
        $data = User::listByWhere($params);
//        dd(\DB::getQueryLog());
        return $this->success('查询成功',$data);
    }

    /**
     * 修改会员状态
     * URL POST:/admin/member/updateStatus
     * @param Request $request
     * @param int user_id 用户ID
     * @return mixed
     */
    public function updateStatus(Request $request){
        $params = $request->only(['user_id']);
        if (!array_key_exists('user_id',$params) || empty($params['user_id'])) {
            return $this->error('缺少用户ID');
        }
        $user = User::find($params['user_id']);
        if (!$user) {
            return $this->error('用户不存在');
        }
        $status = $user->status == 1 ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['user_id']];
        $field = ['status'=>$status];
        $res = User::modify($where,$field);
        if ($res === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 导出
     * URL GET:/admin/member/export
     * @param Request $request
     * @param int type 1用户名称 2用户手机
     * @param string keyword 关键字
     * @return mixed
     */
    public function export(Request $request){
        $params = $request->only(['keyword']);
        // 设置内存
        ini_set('memory_limit','1000M');
        //设置超时限制为0分钟(无限制, 默认30s)
        set_time_limit(0);
        $params['with'][] = ['file'=>function($query){
            $query->select('id','path');
        }];
        // 关键字
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        $type = isset($params['type']) ? $params['type'] : 1;

        if (!empty($keyword)) {
            switch ($type) {
                case 1:// 用户名称
                    $params['where'][] = ['name','like','%'.$keyword.'%'];
                    break;
                case 2:
                    $params['where'][] = ['mobile','like','%'.$keyword.'%'];
                    break;
            }
        }
        $data = User::getAll($params);
        //session()->put('excel_data');
        return Excel::download(new \App\Excel\UserExport($data), time().'_用户导出.xlsx');
    }

    /**
     * 用户添加、编辑
     * URL POST:/admin/member/store
     * @param Request $request
     * @param int id 用户ID
     * @param string name 名称
     * @param string mobile 手机
     * @return mixed
     */
    public function store(Request $request){
        $params = $request->only(['id','name','mobile']);
        $id = isset($params['id']) ? $params['id'] : '';
        $validator = Validator::make($params,[
            'name'              => ['required'],
            'mobile'            => ['nullable','regex:/^1[3456789]\d{9}$/'],
        ],[
            'name.required'         => '用户名称是必须的',
            'mobile.required'       => '用户手机是必须的',
            'mobile.regex'          => '手机格式错误',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        if ($id == 0) {
            $user = new User();
        }else{
            $user = User::find($id);
            if (!$user) {
                return $this->error('用户不存在');
            }
        }
        $user->name             = $params['name'];
        $user->mobile           = isset($params['mobile']) ? $params['mobile'] : '';
        $result = $user->save();
        if ($result) {
            return $this->success('成功');
        }
        return $this->error('失败');
    }

    /**
     * 用户删除
     * URL POST:/admin/member/delete
     * @param Request $request
     * @param array ids 用户ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params) || empty($params['ids'])) {
            return $this->error('缺少用户ID');
        }
        $res = User::whereIn('id',$params['ids'])->delete();
        if ($res) {
            return $this->success('删除成功');
        }
        return $this->error('删除失败');
    }
}